/*
 * @Date: 2023-02-18 21:05:28
 * @LastEditTime: 2023-10-20 18:30:44
 * 介绍:
 */
import { HttpRequest, MyCongfig } from "@/utils/HttpRequest/HttpRequest";
import useSysStore from "@/store/useSysStore";
import { getSystemInfoCache } from "@/sdk/rewriteUni";
import { isObject } from "lodash";
const env = import.meta.env;
let baseURL = "";
if (env.VITE_PROXY == "1") {
  baseURL + env.VITE_API_PREFIX; //配置默认请求地址--跨域代理
} else {
  baseURL = env.VITE_BASE_URL + env.VITE_API_PREFIX; //配置默认请求地址--无代理
}

const myCongfig: MyCongfig = {
  isSuccess(data) {
    const code = data?.code;
    const err = data?.err;
    if (typeof err === "number") return err === 0;
    return code === 1;
  },
  returnFailMsg(data) {
    return data?.msg || "";
  },
  returnSuccessMsg(data) {
    return data?.msg || "";
  },
};

const defaHttp = new HttpRequest(
  {
    timeout: 1000 * 60 * 3,
    baseURL,
  },
  myCongfig
);
defaHttp.luch.interceptors.request.use((config) => {
  config.data = {
    ...getRequestBaseData(),
    ...config.data,
  };
  return config;
});
defaHttp.luch.interceptors.response.use((res) => {
  if (!isObject(res.data)) {
    console.error("接口返回类型错误", res);
    return Promise.resolve({
      status: false,
    });
  }
  res.data = {
    ...res.data,
    status: myCongfig.isSuccess(res.data),
  };
  return Promise.resolve(res.data);
});

function getRequestBaseData() {
  const sysStore = useSysStore();
  const systemInfo = getSystemInfoCache();
  return {
    client_id: systemInfo.deviceId,
    ...sysStore.requestBaseData,
  };
}
export { defaHttp, baseURL };
export namespace Api {
  export interface Res<T> {
    code: number;
    msg: string;
    status: boolean;
    data: T;
  }
}

export namespace PagingApi {
  /**请求分页接口返res类型 */
  export type Res<T extends any[] = any[]> = Api.Res<Data<T>>;
  /**分页data类型 */
  export interface Data<T extends any[] = any[]> {
    /**当前页码数 */
    current_page: number;
    data: T;
    /**第一页 */
    first_page: string;
    /**尾页 */
    last_page: number;
    /**每页数据长度 */
    per_page: number;
    /**总数 */
    total: number;
  }

  /**分页参数 */
  export interface Req {
    page: number;
  }
}
